package online.longzipeng.mywebdemo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import online.longzipeng.mywebdemo.utils.MyJsonUtils;
import org.junit.jupiter.api.Test;

import java.util.List;

/**
 * @Author: lzp
 * @description: json字符串 任意节点取值
 * @Date: 2023/3/1
 */
public class JsonDemo {

	public static void main(String[] args) throws JsonProcessingException {
		String jsonStr = "{\"head\":{\"eye\":{\"left\":\"写轮眼\",\"right\":\"轮回眼\"},\"iq\":250,\"face\":\"英俊的脸\"},\"height\":199}";
		ObjectMapper objectMapper = new ObjectMapper();

		JsonNode jsonNode = objectMapper.readTree(jsonStr);

		String leftEye = jsonNode.get("head").get("eye").get("left").textValue();
		System.out.println(leftEye);

	}

	@Test
	public void test2() throws JsonProcessingException {
		String jsonStr = "{\"array\":[\"lzp\",\"gblw\",\"xpy\"]}";
		ObjectMapper objectMapper = new ObjectMapper();

		JsonNode jsonNode = objectMapper.readTree(jsonStr);
		JsonNode array = jsonNode.get("array");

		List list = objectMapper.treeToValue(jsonNode.get("array"), List.class);
		System.out.println(list);

	}

	@Test
	public void testMyJsonUtils() throws JsonProcessingException {
		String jsonStr = "{\"head\":{\"eye\":{\"left\":\"写轮眼\",\"right\":\"轮回眼\"},\"iq\":250,\"face\":\"英俊的脸\"},\"height\":199,\"likeStudy\":true}";
		MyJsonUtils myJsonUtils = MyJsonUtils.getInstance();
		JsonNode jsonNode = myJsonUtils.getValueByKeyPath(jsonStr, "head.eye.left");

		System.out.println(jsonNode.textValue());
		System.out.println(jsonNode.toString());

		System.out.println("============================ 直接获取值 =====================");
		String leftEye = myJsonUtils.getValueByKeyPath(jsonStr, "head.eye.left", String.class);
		Integer height = myJsonUtils.getValueByKeyPath(jsonStr, "height", Integer.class);
		Boolean likeStudy = myJsonUtils.getValueByKeyPath(jsonStr, "likeStudy", Boolean.class);

		System.out.println(leftEye);
		System.out.println(height);
		System.out.println(likeStudy);


	}

}
